package com.briup.pts.service.impl;

import cn.hutool.core.util.StrUtil;
import com.briup.pts.entity.ManagerFenceHouse;
import com.briup.pts.entity.ManagerFenceHouseExample;
import com.briup.pts.entity.ManagerHurdles;
import com.briup.pts.entity.ManagerHurdlesExample;
import com.briup.pts.entity.extend.ManagerFenceHouseExt;
import com.briup.pts.exception.ServiceException;
import com.briup.pts.mapper.ManagerFenceHouseMapper;
import com.briup.pts.mapper.ManagerHurdlesMapper;
import com.briup.pts.mapper.extend.ManagerFenceHouseExtMapper;
import com.briup.pts.result.ResultCode;
import com.briup.pts.service.FenceHouseService;
import com.briup.pts.utils.RandomStringGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class FenceHouseServiceImpl implements FenceHouseService {
    @Autowired
    ManagerFenceHouseMapper managerFenceHouseMapper;
    @Autowired
    ManagerHurdlesMapper managerHurdlesMapper;
    @Autowired
    ManagerFenceHouseExtMapper managerFenceHouseExtMapper;

    @Override
    public PageInfo<ManagerFenceHouse> findByPage(int pageNum, int pageSize, String fhName) {
        // 1、根据分页信息，开启分页
        PageHelper.startPage(pageNum, pageSize);
        // 2、获得一个集合。分页思路就是对这个集合进行筛选
        ManagerFenceHouseExample managerFenceHouseExample = new ManagerFenceHouseExample();
        ManagerFenceHouseExample.Criteria criteria = managerFenceHouseExample.createCriteria();
        if (!StrUtil.isEmpty(fhName)) {
            criteria = criteria.andFhNameLike("%" + fhName + "%");
        }
        List<ManagerFenceHouse> managerFenceHouses = managerFenceHouseMapper.selectByExample(managerFenceHouseExample);
        // 3、准备分页对象
        return new PageInfo<>(managerFenceHouses);
    }

    @Override
    public void saveOrUpdate(ManagerFenceHouse managerFenceHouse) {
        // 根据传入对象的fhId区分新增和更新
        String fhId = managerFenceHouse.getFhId();
        if (StrUtil.isEmpty(fhId)) {
            // 新增
            String newFhId;
            ManagerFenceHouse existingFenceHouse;
            do {
                // 生成一个新的fhId
                newFhId = RandomStringGenerator.generateRandomString(32);
                // 检查新生成的fhId是否已存在
                existingFenceHouse = managerFenceHouseMapper.selectByPrimaryKey(newFhId);
            } while (existingFenceHouse != null); // 当fhId已存在时，继续循环生成新的fhId

            // 插入新的栏舍记录
            managerFenceHouse.setFhId(newFhId);
            int insertResult = managerFenceHouseMapper.insert(managerFenceHouse);

            // 判断是否插入成功
            if (insertResult != 1) {
                throw new RuntimeException(ResultCode.FAIL + "Failed to insert new ManagerFenceHouse");
            }
        } else {
            // 更新
            int updateResult = managerFenceHouseMapper.updateByPrimaryKeySelective(managerFenceHouse);

            // 判断是否更新成功（通常updateByPrimaryKeySelective返回影响的行数）
            if (updateResult != 1) {
                throw new ServiceException(ResultCode.FAIL + "Failed to update ManagerFenceHouse");
            }
        }
    }

    @Override
    public void removeById(String fhId) {
        ManagerHurdlesExample managerHurdlesExample = new ManagerHurdlesExample();
        managerHurdlesExample.createCriteria().andHFenceIdEqualTo(fhId);
        List<ManagerHurdles> managerHurdles = managerHurdlesMapper.selectByExample(managerHurdlesExample);
        if (managerHurdles.isEmpty()){
            managerFenceHouseMapper.deleteByPrimaryKey(fhId);
        } else {
            throw new ServiceException(ResultCode.DATA_CAN_NOT_DELETE+"栏舍下有栏圈信息，无法删除。");
        }
    }

    @Override
    public void removeBatch(List<String> ids) {
        // 只有要删除的栏舍信息都不存在，才响应 数据不存在或者已经删除 的错误信息
        ManagerFenceHouseExample managerFenceHouseExample = new ManagerFenceHouseExample();
        managerFenceHouseExample.createCriteria().andFhIdIn(ids);
        List<ManagerFenceHouse> managerFenceHouses = managerFenceHouseMapper.selectByExample(managerFenceHouseExample);
        if (managerFenceHouses.isEmpty()){
            throw new ServiceException(ResultCode.DATA_IS_EMPTY);
        }

        // 只要有一条栏舍信息被删除，就代表操作成功
        AtomicInteger count = new AtomicInteger();
        managerFenceHouses.forEach((managerFenceHouse)->{
            ManagerHurdlesExample managerHurdlesExample = new ManagerHurdlesExample();
            String fhId = managerFenceHouse.getFhId();
            managerHurdlesExample.createCriteria().andHFenceIdEqualTo(fhId);
            List<ManagerHurdles> managerHurdles = managerHurdlesMapper.selectByExample(managerHurdlesExample);
            if (managerHurdles.isEmpty()){
                managerFenceHouseMapper.deleteByPrimaryKey(fhId);
                count.getAndIncrement();
            }
        });

        // 只有要删除的栏舍信息都有关联的栏圈信息，才响应 数据关联其他数据，无法删除 的错误信息
        if (count.get() == 0){
            throw new ServiceException(ResultCode.DATA_CAN_NOT_DELETE);
        }
    }

    @Override
    public ManagerFenceHouseExt findById(String id) {
        return managerFenceHouseExtMapper.selectHouseAndHurdlesById(id);
    }
}
